package com.podmanager.data;

import java.io.File;
import com.podmanager.UI.*;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.support.v4.widget.SimpleCursorAdapter;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;


public class ImageCursorAdapter extends SimpleCursorAdapter {
	private ListView mListView=null;
	
	public ImageCursorAdapter(Context context, int layout, Cursor c,
			String[] from, int[] to, int flags) {
		super(context, layout, c, from, to, flags);
	}
	private ListView setListView(View v)
	{
		ListView lv=null;
		while (v!=null)
		{
			if(v.toString().contains("android.widget.ListView"))
			{
				lv = (ListView) v;
				break;
			}
			v=(View)v.getParent();
		}
		return lv;
	}
    @Override
    public void setViewImage(ImageView imageView, String id) {
    	switch(imageView.getId())
    	{
    	case R.id.episodes_item_download_button:
    		File f=new File(id);
    		if(f.exists())
    			imageView.setImageDrawable(this.mContext.getResources().getDrawable(R.drawable.delete));
    		else
    			imageView.setImageDrawable(this.mContext.getResources().getDrawable(R.drawable.download));

			imageView.setContentDescription(id);
    		setDownloadClickListener(imageView);
    		break;
    	case R.id.episodes_item_playlist_button:
    		if(id.equals("0"))
    		{
    			imageView.setImageDrawable(this.mContext.getResources().getDrawable(R.drawable.add_to_playlist));
    			imageView.setContentDescription("Add to Playlist");
    		}
    		else
			{
    			imageView.setImageDrawable(this.mContext.getResources().getDrawable(R.drawable.remove_from_playlist));
    			imageView.setContentDescription("Remove from Playlist");
			}
    		setPlaylistClickListener(imageView);
    		break;
    	case R.id.episodes_item_read_button:
    		long readPosition=0;
			try {
				readPosition = Long.parseLong(id);
			} catch (Exception e) {
				e.printStackTrace();
			}
    		
    		if(readPosition!=0)
    		{
    			imageView.setImageDrawable(this.mContext.getResources().getDrawable(R.drawable.read));
    			imageView.setContentDescription("is Read");
    		}
    		else//1 is used to indicate file completed playback
    		{
    			imageView.setImageDrawable(this.mContext.getResources().getDrawable(R.drawable.rss_plain));
    			imageView.setContentDescription("is Unread");
    		}
    		setReadClickListener(imageView);
    		break;
    	default:
			if(validateFileAndSetBitmap(imageView, id))return;//exit if episode image is properly set
			imageView.setImageResource(R.drawable.loading);
			imageView.setContentDescription(id);
			new AsyncTask<ImageView, Void, String>(){
				ImageView mImageView=null;
				@Override
				protected String doInBackground(ImageView... params) {
					mImageView=params[0];
					String imagePath=mImageView.getContentDescription().toString();
					String selection= PMDatabase.EPISODES.EPI_IMAGE_PATH+"='"+params[0].getContentDescription()+"'";
					ContentResolver cr = mImageView.getContext().getContentResolver();
					Cursor c =cr.query(DBContentProvider.EPISODES_URI,					//uri/table 
							new String[]{PMDatabase.EPISODES.SUB_ROW_ID}, 	//columns
							selection, null, null);							//selection, args, sort
					if(c==null)return null;
					if(c.getCount()<1)return null;
					c.moveToFirst();
					int subscriptionID=c.getInt(c.getColumnIndex(PMDatabase.EPISODES.SUB_ROW_ID));
					c.close();
					c=cr.query(DBContentProvider.SUBSCRIPTION_URI,				//URI 
							new String[]{PMDatabase.SUBSCRIPTIONS.SUB_IMAGE_PATH},//columns/projection 
							PMDatabase.SUBSCRIPTIONS.KEY_ROW_ID+"="+subscriptionID, //selection
							null, null);										//selectionArgs, sort
					if(c==null)return null;
					if(c.getCount()<1)return null;
					c.moveToFirst();
					String result=c.getString(c.getColumnIndex(PMDatabase.SUBSCRIPTIONS.SUB_IMAGE_PATH));
					c.close();
					if (result==null || result.equals(""))
						result=imagePath;
					ContentValues values =new ContentValues();
					values.put(PMDatabase.EPISODES.EPI_IMAGE_PATH, result);
					cr.update(DBContentProvider.EPISODES_URI, values, selection, null);
					
					return result;
				}

				@Override
				protected void onPostExecute(String result) {
					super.onPostExecute(result);
					if(result==null || mImageView==null)return;
					validateFileAndSetBitmap(mImageView, result);
				}
				
			}.execute(imageView);
    	}
        
    }
	private void setDownloadClickListener(ImageView imageView) {
    	imageView.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View arg0) {
	        	if(mListView==null)
	        		mListView=setListView(arg0);
	        	ImageView iv=(ImageView)arg0;
	        	String strFile = arg0.getContentDescription().toString();
	        	File file=new File(strFile);
	        	if (file.exists())
	        	{
	        		//if file exists, that means user is choosing to delete...delete the file, AND remove from playlist
	        		new AsyncTask<String, Void, Void>(){
						@Override
						protected Void doInBackground(String... params) { 
							File f=new File(params[0]);
			        		f.delete();
			        		
							ContentValues values = new ContentValues();
							values.put(PMDatabase.EPISODES.IS_IN_PLAYLIST, 0);
							String selection=PMDatabase.EPISODES.FILE_PATH+"='"+params[0]+"'";
							mContext.getContentResolver().update(
									DBContentProvider.EPISODES_URI, 
									values, selection, null);
							updateDownloadedEpisodes(params[0]);
							return null;
						}}
	        		.execute(strFile);
	    			iv.setImageDrawable(mContext.getResources().getDrawable(R.drawable.download));
					Toast.makeText(mContext, "Episode deleted", Toast.LENGTH_LONG).show();
	        	}
	        	else
	        	{
					View item = (View)arg0.getParent().getParent().getParent();
					long id=mListView.getItemIdAtPosition(mListView.getPositionForView(item));
					Log.d("download Listener", "item '" + id +"' was clicked");
	    			iv.setImageDrawable(mContext.getResources().getDrawable(R.drawable.delete));
	    			TextView tv=((TextView)item.findViewById(R.id.episodes_item_title));
	    			String title=tv.getText().toString();
					Toast.makeText(mListView.getContext(), "Download Podcast Started", Toast.LENGTH_LONG).show();
					new DownloadPodcastAsyncTask(mListView.getContext(), title).execute(Long.toString(id));
	        	}
			}
			
		});
	}
	
	private void updateDownloadedEpisodes(String filePath) {
		try {
			Cursor c = mContext.getContentResolver().query(DBContentProvider.EPISODES_URI, 
															new String[] {PMDatabase.EPISODES.SUB_ROW_ID}, 
															PMDatabase.EPISODES.FILE_PATH + "=" + String.format("'%s'", filePath), null, null);
			c.moveToFirst();
			long subscription_id = c.getLong(0);
			c.close();
			
			c = mContext.getContentResolver().query(DBContentProvider.SUBSCRIPTION_URI, 
					new String[] {PMDatabase.SUBSCRIPTIONS.EPISODES_DOWNLOADED}, 
					PMDatabase.SUBSCRIPTIONS.KEY_ROW_ID + "=" + subscription_id, null, null);
			c.moveToFirst();
			long episodes_downloaded = c.getLong(0);
			c.close();
			
			if (episodes_downloaded > 0)
				episodes_downloaded--;
			
			String filter = PMDatabase.SUBSCRIPTIONS.KEY_ROW_ID + "=" + subscription_id;
			ContentValues args = new ContentValues();
			args.put(PMDatabase.SUBSCRIPTIONS.EPISODES_DOWNLOADED, episodes_downloaded);

			int rows = mContext.getContentResolver().update(DBContentProvider.SUBSCRIPTION_EPI_DOWNLOADED_URI, 
					args, filter, null);

			
			System.out.println("updated downloaded episode row " + rows);
		} catch (Exception e) 
		{ 
			e.printStackTrace();
		}
		
	}
	
	private void setPlaylistClickListener(ImageView imageView) {    		
		imageView.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View arg0) {
	        	if(mListView==null)
	        		mListView=setListView(arg0);
				View item = (View)arg0.getParent().getParent().getParent();
				long id=mListView.getItemIdAtPosition(mListView.getPositionForView(item));
				Log.d("playlist Listener", "item '" + id +"' was clicked");
				ImageView iv = (ImageView) arg0;
				if(iv.getContentDescription()=="Add to Playlist")
				{
					ContentValues values = new ContentValues();
					values.put(PMDatabase.EPISODES.IS_IN_PLAYLIST, 1);
					mContext.getContentResolver().update(
							Uri.withAppendedPath(DBContentProvider.EPISODES_URI,"/"+id), 
							values, null, null);
					iv.setContentDescription("Remove from Playlist");
	    			iv.setImageDrawable(mContext.getResources().getDrawable(R.drawable.remove_from_playlist));
					Toast.makeText(mContext, "Episode added to playlist.", Toast.LENGTH_LONG).show();
					
				}
				else
				{
					ContentValues values = new ContentValues();
					values.put(PMDatabase.EPISODES.IS_IN_PLAYLIST, 0);
					mContext.getContentResolver().update(
							Uri.withAppendedPath(DBContentProvider.EPISODES_URI,"/"+id), 
							values, null, null);
					iv.setContentDescription("Add to Playlist");
	    			iv.setImageDrawable(mContext.getResources().getDrawable(R.drawable.add_to_playlist));
					Toast.makeText(mContext, "Episode removed from playlist.", Toast.LENGTH_LONG).show();
				}
			}
		});
	}
	
	
	
	private void setReadClickListener(ImageView imageView) {
		imageView.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View arg0) {
	        	if(mListView==null)
	        		mListView=setListView(arg0);
				View item = (View)arg0.getParent().getParent().getParent();
				long id=mListView.getItemIdAtPosition(mListView.getPositionForView(item));
				Log.d("read Listener", "item '" + id +"' was clicked");
				ImageView iv = (ImageView) arg0;
				if(iv.getContentDescription()=="is Unread")
				{
					ContentValues values = new ContentValues();
					values.put(PMDatabase.EPISODES.IS_READ, 1);
					values.put(PMDatabase.EPISODES.POSITION, 0);
					mContext.getContentResolver().update(
							Uri.withAppendedPath(DBContentProvider.EPISODES_URI,"/"+id), 
							values, null, null);
					iv.setContentDescription("is Read");
	    			iv.setImageDrawable(mContext.getResources().getDrawable(R.drawable.read));
					Toast.makeText(mContext, "Episode marked Read.", Toast.LENGTH_LONG).show();
				}
				else
				{
					ContentValues values = new ContentValues();
					values.put(PMDatabase.EPISODES.IS_READ, 0);
					values.put(PMDatabase.EPISODES.POSITION, 0);
					mContext.getContentResolver().update(
							Uri.withAppendedPath(DBContentProvider.EPISODES_URI,"/"+id), 
							values, null, null);
					iv.setContentDescription("is Unread");
	    			iv.setImageDrawable(mContext.getResources().getDrawable(R.drawable.rss_plain));
					Toast.makeText(mContext, "Episode marked Unread.", Toast.LENGTH_LONG).show();
				}
			}
		});
	}	
	private Boolean validateFileAndSetBitmap(ImageView iv, String file){
		if(!new File(file).exists())		return false;
        Bitmap b = BitmapFactory.decodeFile(file);
        if(b.getWidth()<5 ||b.getHeight()<5)return false;
        iv.setImageBitmap(b);
        return true;
	}
}